/**
 * crypto加解密
 */

import CryptoJS from 'crypto-js'

const AES_KEY = '4vjc6zw888b53vgw' // 后端提供的key

/**
 * AES加密
 */
export const AESEncrypt = (data) => {
	if (typeof data === 'object') {
		try {
			data = JSON.stringify(data)
		} catch (error) {
			console.log('加密失败:', error)
		}
	}
	const key = CryptoJS.enc.Utf8.parse(AES_KEY)
	const srcs = CryptoJS.enc.Utf8.parse(data)
	const encrypted = CryptoJS.AES.encrypt(srcs, key, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	})
	return encrypted.toString()
}

/**
 * AES解密
 */
export const AESDecrypt = (data) => {
	const key = CryptoJS.enc.Utf8.parse(AES_KEY)
	const decrypt = CryptoJS.AES.decrypt(data, key, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	})
	return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

/**
 * base64 加密
 * @param data
 */
export const Encrypt = (data) => {
	if (typeof data === 'object') {
		try {
			data = JSON.stringify(data)
		} catch (error) {
			console.log('加密失败:', error)
		}
	}
	const wordArray = CryptoJS.enc.Utf8.parse(data)
	const base64 = CryptoJS.enc.Base64.stringify(wordArray)
	return base64
}
